﻿/*文件注释
 * ===============================================================================
 * 说明：
 * 作者：曾永佑
 * 版本：v1.0
 * 创建日期：2013-11-1
 * 完成日期： 
 * 修改纪录：  
 * ===============================================================================
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace SRF.Common.Logging
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class LogAttribute : System.Web.Mvc.FilterAttribute, System.Web.Mvc.IActionFilter
    {
        public LogAttribute()
        {
        }

        bool _logDebug = true;
        /// <summary>
        /// 是否写debug日志
        /// </summary>
        public bool LogDebug
        {
            get { return _logDebug; }
            set { _logDebug = value; }
        }

        public static Func<string> GetCurrentUserId;
        
        public void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
        { 
            var url = filterContext.HttpContext.Request.Url.ToString();

            if (LogDebug)
            {
                SRF.Common.Logging.LogManager.GetLogger("UrlRequest").Debug(url);
            }

            try
            {
                IUrlRequestLogger urlRequestLog = ObjectHelper.GetObject<IUrlRequestLogger>();
                if (urlRequestLog != null)
                {
                    var userId = GetCurrentUserId == null ? null : GetCurrentUserId.Invoke();
                    urlRequestLog.Write(filterContext.HttpContext.Request, userId);
                } 
            }
            catch
            {
            }
        }
        public void OnActionExecuted(System.Web.Mvc.ActionExecutedContext filterContext)
        {

        }
    }
}